<template>
	<view class="relative" style="min-height: 100vh;">
		<view class="absolute w-screen" style="z-index: -100; background: linear-gradient(to top, #FF9701 0%, #F5F6FB 100%); top: 660rpx; left:0; height: calc(100% - 660rpx);"></view>
		<view class="relative" style="z-index: 90;">
			<map  id="myMap" class="w-full" style="height: 660rpx;" 
			:latitude = "mapConf.latitude"
			:longitude = "mapConf.longitude"
			:markers = "mapConf.markers"
			show-location
			min-scale='8'
			@regionchange = "regionChange"
			@markertap = "markerTap"
			></map>
			<picker class="absolute" style="top: 30rpx; left: 24rpx;"  mode="region" level="city" @change="cityChange">
				<view class="flex flex-row align-items-center">
					<view class="text-15 text-bold">{{selectedCity.fullname}}</view>
					<view class="ml-2"><image src="/static/arrow-a.png" style="width: 18rpx; height: 18rpx;"></image></view>	
				</view>
			</picker>
			<cover-view v-if="marker_address" class="absolute flex flex-col align-items-center" style="bottom: 50%; left: 50%; transform: translate(-50%, 0);" >
				<cover-view style="align-self: start; background-color: #006AFF; font-size: 18rpx;" class="px-5 py-3 text-white">当前位置</cover-view>
				<cover-view style="border: 1px solid #aaa; border-radius: 0 10rpx 10rpx 10rpx; font-size: 22rpx;" class="px-8 py-5 bg-white text-bold">{{marker_address}}</cover-view>
				<cover-view style="width: 2px; height: 15px; background-color: #006AFF;"></cover-view>
			</cover-view>
		</view>
		<view class="px-10 static" style="margin-top: 20rpx; z-index: 100;" >
			<view class="px-15 py-10 rounded-lg bg-white text-13" style="box-shadow: 0 0 5px 0px rgba(0,0,0,0.3);">
				<view class="mb-5 flex flex-row align-items-center" style="height: 65rpx;">
					<view class="font-0 mr-8 ml-8" style="width: 10rpx; height: 10rpx; border-radius: 50%; background-color: #FF9701;"></view>
					<view class="flex-1 text-black ellipsis">{{search_address}}</view>
					<view class="p-5" @tap="chooseLocation">
						<image style="width: 38rpx; height: 38rpx;" src="/static/address-orange.png" ></image>
					</view>
				</view>
				<view class="flex flex-row align-items-center" style="height: 65rpx; background-color: #F3F3F3; border-radius: 8rpx;" @tap="chooseLocation">
					<view class="font-0 mr-8 ml-8" style="width: 10rpx; height: 10rpx; border-radius: 50%; background-color: #0028FF;"></view>
					<view>搜索</view> 
					<!-- <view style="color: #006AFF;">{{search_address}}</view> -->
					<view class="text-bold" >订单位置/附近订单</view>
				</view>
			</view>
		</view>
		<view class="p-10 static">
			<!-- <view v-if="order_num" class="mb-8 px-15 rounded-lg bg-white flex flex-row align-items-center" style="height: 100rpx;">
				<view class="text-bold text-15 flex-1">您有<text class="px-2">{{order_num}}</text>笔订单正在进行中</view>
				<view class="rounded-xs text-center text-12 text-white" style="width: 100rpx; height: 50rpx; line-height:50rpx;background-color: #0094FF;" @tap="navigateTo('/pages/user/order?type=2')">查看</view>
			</view> -->
			<!-- <swiper class="rounded-lg" :style="{'height': category_list.length==1 && category_list[0].length<=5 ? '224rpx': '404rpx'}"  indicator-dots indicator-active-color='#25AFFF' indicator-color='#DDD' style="box-shadow: 0 0 5px 0px rgba(0,0,0,0.3);">
				<swiper-item class="rounded-lg bg-white" v-for="(cate_list, index0) in category_list" :key="index0">
					<view class="flex flex-row flex-wrap px-5 pt-15 pb-25 text-0">
						<view v-for="(cate, index) in cate_list" :key="cate.id" class="w-a-5 text-center" :class="{'mb-20': Math.ceil((index+1)/5)!=Math.ceil(cate_list.length/5)}" @tap="changeCate(cate.id)">
							<image class="" style="width: 100rpx; height: 100rpx;" :src="cate.img"></image>
							<view class="text-bold text-13 mt-3" style="color: #5E5E5E;">{{cate.name}}</view>
						</view>
					</view>
				</swiper-item>
			</swiper> -->
			
			<view class="rounded-lg" style="box-shadow: 0 0 5px 0px rgba(0,0,0,0.3);">
				<view class="rounded-lg bg-white" >
					<view class="flex flex-row flex-wrap px-5 pt-15 pb-15 text-0">
						<view v-for="(item, index) in transport_scene_list_arr" :key="index" class="w-a-5 text-center" :class="{'mb-20': Math.ceil((index+1)/5)!=Math.ceil(transport_scene_list_arr.length/5)}" @tap="changeScene(item.name)">
							<image class="" style="width: 100rpx; height: 100rpx;" :src="item.img"></image>
							<view class="text-bold text-13 mt-3" style="color: #5E5E5E;">{{item.name}}</view>
						</view>
					</view>
				</view>
			</view>
			<view class="p-10 rounded-lg bg-white mt-8 mb-20">
				<view class="flex flex-row align-items-center px-5" style="">
					<!-- <view class="theme-bg mr-5" style="width: 20rpx; height: 40rpx; border: 2rpx solid #B7BBBC;"></view> -->
					<view class="text-bold text-14">订单列表</view>
					<view class="flex-1"></view>
					<view class="flex flex-row align-items-center text-14 mr-20" @tap="changeTimeOrder()">
						<view class="pr-3">时间</view>
						<view class="flex flex-col">
							<image v-if="time_order=='asc'" class='arrow-up' src="/static/arrow-a.png"></image>
							<image v-else class='arrow-up' src="/static/arrow.png"></image>
							<image v-if="time_order=='desc'" class='arrow-down' src="/static/arrow-a.png"></image>
							<image v-else class='arrow-down' src="/static/arrow.png"></image>
						</view>
					</view>
					<view class="flex flex-row align-items-center text-14" @tap="changePriceOrder()">
						<view class="pr-3">价格</view>
						<view class="flex flex-col">
							<image v-if="price_order=='asc'" class='arrow-up' src="/static/arrow-a.png"></image>
							<image v-else class='arrow-up' src="/static/arrow.png"></image>
							<image v-if="price_order=='desc'" class='arrow-down' src="/static/arrow-a.png"></image>
							<image v-else class='arrow-down' src="/static/arrow.png"></image>
						</view>
					</view>
				</view>
				<view class="mt-7">
					<template v-for="(task,index) in task_list" :key="task.id">
						<view class="flex flex-row border-2 theme-border rounded-base align-items-center mb-12" style="line-height: 40rpx; font-size: 25rpx" @tap="navigateTo('/pages/task/detail?id='+task.id)">
							<view class="p-10" style="width: 100rpx; height: 100rpx;">
								<image v-if="transport_scene_list_obj[task.transport_scene]" class="w-full h-full" :src="transport_scene_list_obj[task.transport_scene].img"></image>
							</view> 
							<view v-if="task.category_id == 1" class="my-7 flex-1 pr-6 pl-6 " style="line-height: 45rpx;">
								<view class="flex flex-row">
									<view class="flex-1">货运场景：{{task.transport_scene}}</view>
									<view class="theme-color">查看详情</view>
								</view>
								<view>货物种类：{{task.transport_type}}</view>
								<view>上门时间：{{task.exec_at}}</view>
								<view class="flex flex-row">
									<view class="flex-1">订单金额：￥{{task.money}}</view>
									<image style="width: 150rpx; height: 50rpx;" src="/static/r-btn1.png"></image>
								</view>
							</view>
							<view v-else class="my-5 flex-1 pr-6">
								<view class="flex flex-row">
									<view class="flex-1">名称：{{task.name}}</view>
									<view class="theme-color">查看详情</view>
								</view>
								<view>地址：{{task.place}}</view>
								<view>时间：{{task.exec_at}}</view>
								<view class="flex flex-row">
									<view class="flex-1">价格：￥{{task.money}}</view>
									<image style="width: 150rpx; height: 50rpx;" src="/static/r-btn1.png"></image>
								</view>
							</view>
						</view>
					</template>
				</view>
				<view class="text-14 text-center mb-10" style="color: #000"> ~ 暂无更多订单 ~ </view>
			</view>
		</view>
		
		<view class="text-center pb-5 absolute" style="color: #8F590C; font-size: 12px;  bottom: 0; left: 50%; transform: translate(-50%,0);"><span class="pr-6">艾飞科技</span><span>技术支持</span></view>
	</view>
</template>

<script>
	import request from '/utils/request.js';
	import {login} from '@/utils/login.js';
	import {checkAndOpenScope} from '/utils/util.js';
	import { mapState, mapMutations } from 'vuex'
	export default {
		data() {
			return {
				is_ready: false,
				category_list: [],
				task_list: [],
				page: 1,
				has_more: true,
				category_id: 0,   
				time_order: 'asc',   
				price_order: '',
				mapCtx: null,
				mapConf: {
					latitude: '',
					longitude:'',
					// markers:[
					// 	{
					// 		id: 1,
					// 		latitude: 24.44579,
					// 		longitude: 118.08243,
					// 		iconPath: 'https://feitu.smartspark.xyz/upload/39/275a4ab4ca9571f770fc11a91c134a.png',
					// 		width: 50,
					// 		height: 50,
					// 		joinCluster: true,
					// 		collisionRelation: 'marker'
					// 	},
					// ],
					setting: {
						
					}
				},
				// 初始化选点，福州
				selectedCity: {
					// fullname: "福州市",
					// latitude: 26.074286, 
					// longitude: 119.296411,
				},
				// 正在进行中的订单数量
				order_num: 0,
				search_address: '',
				region_change_count: 0,
				task_list_in_map: [],
				
				
				defaultSelectedCity: {
					fullname: "福州市",
					latitude: 26.074286, 
					longitude: 119.296411,
				},
				
				transport_scene_list_arr: [],
				transport_scene_list_obj: {},
				
				marker_address: '',
				show_address: ''
			}
		},
		computed: {
			...mapState(['mapKey'])
		},
		onLoad() {
			// this.getCategoryList();
			// 获取货运配置数据
			request.post('transport/config').then(res=>{
				// this.transport_distance_list = res.transport_distance_list;
				// this.transport_scene_list = res.transport_scene_list;
				// this.transport_type_list = res.transport_type_list;
				this.transport_scene_list_arr = res.transport_scene_list_arr;
				this.transport_scene_list_obj = res.transport_scene_list_obj;
			})
		},
		onShow() {
			if(!this.selectedCity.fullname && this.is_ready){
				this.initMap();
			}
			this.category_id = 0;
			this.time_order = 'asc';
			this.price_order = '';
			this.transport_scene = '';
			this.getTaskList(true);
		},
		onReachBottom() {
			this.getTaskList();
		},
		onShareAppMessage() {
			return {
			  title: '飞兔接单',
			  path: '/pages/task/list',
			  // imageUrl : ''
			}
		},
		onShareTimeline() {
			return {
			  title: '飞兔接单',
			  // query: '',
			  // imageUrl : ''
			}
		},
		onReady() {
			this.is_ready = true;
			this.initMap();
		},
		onUnload () {
		 
		},
		methods: {
			initMap(){
				var that = this;
				this.mapCtx = wx.createMapContext('myMap')
				// 移动到定位点，需要先授权
				checkAndOpenScope('scope.userLocation', '需要您授权当前位置信息，是否前往设置页面开启？').then(() => {
					this.mapCtx.moveToLocation({
						success(res){
							console.log('moveToLocation,success', res);
							// 等待1秒，渲染完成，才能获取到正确的位置
							setTimeout(()=>{
								that.mapCtx.getCenterLocation({
									success(res){
										console.log('getCenterLocation,success', res);
										const latitude = res.latitude
										const longitude = res.longitude
										that.mapConf.latitude = latitude;
										that.mapConf.longitude = longitude;
										that.toAddr(latitude, longitude, function(data){
											that.search_address = data.search_address;
											that.marker_address = data.marker_address;
										});
									},
									fail(err){
										console.log('getCenterLocation,fail', err);
									}
								})
							}, 1000)
						},
						fail(err){
							console.error('moveToLocation,fail', err);
						}
					});
				}).catch((err) => {
					console.error('授权失败:', err);
				    // 未授权，设定默认的地点
					that.selectedCity.fullname = that.defaultSelectedCity.fullname;
					that.selectedCity.latitude = that.defaultSelectedCity.latitude;
					that.selectedCity.longitude = that.defaultSelectedCity.longitude;
					that.mapConf.latitude = that.selectedCity.latitude;
					that.mapConf.longitude = that.selectedCity.longitude;
				});
			},
			// 选择地点
			chooseLocation(){
				console.log('选择位置')
				var that = this;
				checkAndOpenScope('scope.userLocation', '需要您授权当前位置信息，是否前往设置页面开启？').then(() => {
					wx.chooseLocation({
						latitude: Number(that.mapConf.latitude),
						longitude: Number(that.mapConf.longitude),
						success(res){
							console.log('chooseLocation，success', res)
							let latitude = res.latitude;
							let longitude = res.longitude;
							that.mapConf.latitude = latitude;
							that.mapConf.longitude = longitude;
							let address = res.address;
							let name = res.name;
							that.toAddr(latitude, longitude, function(data){
								that.search_address = data.province + data.city + data.area + data.street + name;
								that.marker_address = data.marker_address;
							})
						},
						fail(err) {
							console.log('chooseLocation，fail', err)
						}
					})
				})
			},
			// 获取订单分类
			getCategoryList(){
				request.post('/task/categoryList').then(res=>{
					let list = res;
					// 每10个分为一组
					const new_list = [];
					for (let i = 0; i < list.length; i += 10) {
						new_list.push(list.slice(i, i + 10));
					}
					this.category_list = new_list;
				})
			},
			// 获取订单列表 
			getTaskList(force = false){
				if(force) {
					this.page = 1;
					this.has_more = true;
				};
				if(!this.has_more) return;
				request.post('/task/taskList', {
					category_id: this.category_id,
					time_order: this.time_order,
					price_order: this.price_order,
					transport_scene: this.transport_scene,
					page: this.page,
					limit: 20,
				}).then(res=>{
					this.task_list = force ? res.list : this.task_list.concat(res.list);
					this.has_more = res.has_more;
					this.page = res.page + 1;
				})
			},
			// 变更场景
			changeScene(scene){
				this.transport_scene = scene;
				this.getTaskList(true);
			},
			// 变更时间排序
			changeTimeOrder(){
				this.price_order = '';
				switch(this.time_order) {
					case '':
						this.time_order = 'desc';
						break;
					case 'desc':
						this.time_order = 'asc';
						break;
					case 'asc':
						this.time_order = '';
						break;
					default:
						this.time_order = '';
				}
				this.getTaskList(true);
			},
			// 变更价格排序
			changePriceOrder(){
				this.time_order = '';
				switch(this.price_order) {
					case '':
						this.price_order = 'desc';
						break;
					case 'desc':
						this.price_order = 'asc';
						break;
					case 'asc':
						this.price_order = '';
						break;
					default:
						this.price_order = '';
				}
				this.getTaskList(true);
			},
			navigateTo($url){
				uni.navigateTo({
					'url': $url
				})
			},
			// 经纬度解析成地址
			toAddr(lat, lng, callback = null){
				var that = this;
				wx.request({
					url: `https://apis.map.qq.com/ws/geocoder/v1/?key=${that.mapKey}&&location=${lat},${lng}`,  
					header: {
						'content-type': 'application/json' // 默认值
					},
					success (res) {
						console.log('地址逆解析成功', res.data)
						let data = res.data;
						if(data.status != 0) return;
						let ad_info = data.result.ad_info
						that.selectedCity.fullname = ad_info.city;
						that.selectedCity.latitude = ad_info.location.latitude;
						that.selectedCity.longitude = ad_info.location.longitude;
						
						let address_component = data.result.address_component;
						let province = address_component.province;
						let city = address_component.city;
						let district = address_component.district;
						let street = address_component.street;
						
						let address_reference = data.result.address_reference;
						let address = street + address_reference.landmark_l2.title;
						
						let marker_address = province + city + district + street;
						let search_address = province + city + district + address;
						
						if(typeof(callback) == 'function') callback({
							latitude: lat,
							longitude: lng,
							province: province,
							city: city,
							area: district,
							street: street,
							address: address,
							marker_address: marker_address,
							search_address: search_address
						});
					}
				})
			},
			// 改变城市
			cityChange(e){
				console.log(e)
				var that = this;
				let province = e.detail.value[0]
				let city = e.detail.value[1]
				// 地址解析出经纬度
				wx.request({
					url: `https://apis.map.qq.com/ws/geocoder/v1?key=${that.mapKey}&&address=${province}${city}`,  
					header: {
						'content-type': 'application/json' // 默认值
					},
					success (res) {
						console.log('地址解析成功', res.data)
						let data = res.data;
						if(data.status != 0) return;
						let addr = data.result;
						that.selectedCity.fullname = addr.address_components.city;
						that.selectedCity.latitude = addr.location.lat;
						that.selectedCity.longitude = addr.location.lng;
						that.mapConf.latitude = that.selectedCity.latitude;
						that.mapConf.longitude = that.selectedCity.longitude;
					}
				})
			},
			// 视野改变，获取当前视野经纬度范围，请求获取当前视野任务，间隔1秒，一秒后视野不变化才请求接口
			regionChange(e){
				console.log('regionChange', e)
				if(e.type!=='end') return;
				var that = this;
				let cur_region_change_count = this.region_change_count + 1
				this.region_change_count = cur_region_change_count;
				setTimeout(()=>{
					if(this.region_change_count == cur_region_change_count){
						// 重新逆解析
						that.mapCtx.getCenterLocation({
							success(res){
								console.log('getCenterLocation,success', res);
								const latitude = res.latitude
								const longitude = res.longitude
								that.toAddr(latitude, longitude, function(data){
									that.marker_address = data.marker_address;
									that.mapConf.latitude = data.latitude;
									that.mapConf.longitude = data.longitude;
									if(e.causedBy == 'drag'){
										that.search_address = data.search_address;
									}
								});
							},
							fail(err){
								console.log('getCenterLocation,fail', err);
							}
						})
						// 请求视野数据
						this.mapCtx.getRegion({
							success(res){
								console.log('getRegion,success', res)
								// 请求视野内数据，渲染到地图上
								request.post('/task/taskListInMap', {
									en_lat: res.northeast.latitude,
									en_lng: res.northeast.longitude,
									ws_lat: res.southwest.latitude,
									ws_lng: res.southwest.longitude,
									limit: 20,
								}).then(res=>{
									console.log('taskListInMap', res);
									if(res.list){
										that.task_list_in_map = res.list;
										// 渲染到地图上
										let markers = [];
										that.task_list_in_map.forEach((item)=>{
											markers.push({
												id: item.id,
												latitude: item.lat,
												longitude: item.lng,
												iconPath: that.transport_scene_list_obj[item.transport_scene] ? that.transport_scene_list_obj[item.transport_scene].img : '',
												width: 30,
												height: 30,
												joinCluster: true
											})
										})
										that.mapConf.markers = markers;
									}
								})
							},
							fail(err){
								console.log('getRegion,fail', err)
							}
						})
					}
				}, 1000)
			},
			// 点击标记点，弹窗展示当前任务信息
			markerTap(e){
				console.log('markerTap', e);
				this.navigateTo('/pages/task/detail?id=' + e.markerId);
			},
		}
	}
</script>

<style>
	.arrow-up{
		width: 18rpx; 
		height: 18rpx; 
		transform: rotate(180deg);
		margin-bottom: -2rpx;
		margin-top: 2rpx;
	}
	.arrow-down{
		width: 18rpx; 
		height: 18rpx; 
		margin-top: -2rpx;
	}
</style>
